package com.stars.easyms.base.pointcut;

import com.stars.easyms.base.util.AnnotationUtil;
import org.springframework.aop.ClassFilter;
import org.springframework.util.Assert;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>className: EasyMsAnnotationClassFilter</p>
 * <p>description: EasyMs注解类过滤器</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019/5/10 12:25
 */
public class EasyMsAnnotationClassFilter implements ClassFilter {

    private final List<Class<? extends Annotation>> annotationTypeList = new ArrayList<>();

    private final boolean checkInherited;

    public EasyMsAnnotationClassFilter(Class<? extends Annotation> annotationType, boolean checkInherited) {
        Assert.notNull(annotationType, "Annotation type must not be null");
        this.annotationTypeList.add(annotationType);
        this.checkInherited = checkInherited;
    }

    public EasyMsAnnotationClassFilter(List<Class<? extends Annotation>> annotationTypeList, boolean checkInherited) {
        Assert.notEmpty(annotationTypeList, "Annotation type must not be null");
        this.annotationTypeList.addAll(annotationTypeList);
        this.checkInherited = checkInherited;
    }

    @Override
    public boolean matches(Class<?> clazz) {
        for (Class<? extends Annotation> annotationType : annotationTypeList) {
            boolean isMatch = this.checkInherited ? AnnotationUtil.hasAnnotation(clazz, annotationType) : clazz.isAnnotationPresent(annotationType);
            if (isMatch) {
                return true;
            }
        }
        return false;
    }

    protected List<Class<? extends Annotation>> getAnnotationTypeList() {
        return annotationTypeList;
    }

    protected boolean isCheckInherited() {
        return checkInherited;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        } else if (!(other instanceof EasyMsAnnotationClassFilter)) {
            return false;
        } else {
            EasyMsAnnotationClassFilter otherCf = (EasyMsAnnotationClassFilter) other;
            return this.annotationTypeList.equals(otherCf.annotationTypeList) && this.checkInherited == otherCf.checkInherited;
        }
    }

    @Override
    public int hashCode() {
        return this.annotationTypeList.hashCode() * 40 + (checkInherited ? 1 : 0);
    }

    @Override
    public String toString() {
        return getClass().getName() + ": annotationTypeList(" + this.annotationTypeList + "), checkInherited(" + this.checkInherited + ")";
    }

}
